//
//  CourseDetialVC.m
//  PlayShow
//
//  Created by hff on 2018/4/20.
//  Copyright © 2018年 threeTi. All rights reserved.
//

#import "CourseDetialVC.h"
#import "AppMacro.h"
#import "CatalogTableView.h"
#import "UIColor+Utils.h"
#import "HUD.h"
#import "SVProgressHUD.h"

@interface CourseDetialVC ()<SelectDelegate,UIWebViewDelegate>
{
    int _rowNow;//当前选中的课程
}
//页面布局参数
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *catalogViewHeight; //tableview高度，根据目录内容动态调整

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *conentViewHeight;//scrollview中contentView的高度，根据contentView1、2、3、4动态调整  默认为800
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *ScrollBottomView;//视频下方的scrollview的高度


// 音视频播放区域，高度为1/2宽度
@property (weak, nonatomic) IBOutlet UIView *videoBgView;

// 音视频按钮，整体高度为44
@property (weak, nonatomic) IBOutlet UIView *btnBgView;
@property (weak, nonatomic) IBOutlet UIButton *videoBtn;
@property (weak, nonatomic) IBOutlet UIButton *audioBtn;

// 课程目录列表，默认高度为200
@property (weak, nonatomic) IBOutlet UIView *catalogView;

// 课程详情图文说明- 根据scrollview的contentview自动调整
@property (weak, nonatomic) IBOutlet UIView *contentInfoView;
@property (weak, nonatomic) IBOutlet UIImageView *infoImgView;

@property (weak, nonatomic)CatalogTableView *catalogTV; //显示课程列表的tableview

@property (weak, nonatomic) IBOutlet UIView *topView;//视频顶部黑色层
@property (weak, nonatomic) IBOutlet UIButton *btnback;//返回
- (IBAction)btnbackClick:(id)sender;
@property (weak, nonatomic) IBOutlet UIButton *btnShare;//分享
- (IBAction)btnShareClick:(id)sender;
@property(nonatomic, strong)NSArray *vediodDataArr; // 视频地址
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollTop;

//@property (nonatomic,strong)AVAudioPlayer *audioPlayer;// 音频播放器
@property (nonatomic, strong) AVPlayerViewController *moviePlayerVC;// 视频播放器

@property (nonatomic, strong) UIWebView *webview;
@end

@implementation CourseDetialVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    [self initViewState];
    [self initCatalogView];
    [self initVedioView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     self.navigationController.navigationBar.hidden = YES;
    
}

-(void)initViewState
{
    _btnBgView.layer.borderWidth = 1.0;
    _btnBgView.layer.borderColor = [UIColor colorForHex:PINK_COCOR].CGColor;
    _btnBgView.layer.masksToBounds=YES;
    _btnBgView.layer.cornerRadius = 5.0;

    [_videoBtn  setBackgroundImage:[self imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [_videoBtn  setBackgroundImage:[self imageWithColor:[UIColor colorForHex:PINK_COCOR]] forState:UIControlStateSelected];
    [_audioBtn  setBackgroundImage:[self imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [_audioBtn  setBackgroundImage:[self imageWithColor:[UIColor colorForHex:PINK_COCOR]] forState:UIControlStateSelected];
    
    _videoBtn.selected = YES;
    
}

#pragma mark ---- 初始化目录tableview
-(void)initCatalogView
{
    CatalogTableView *catalogTV = [[CatalogTableView alloc] init];
    [catalogTV initTableView];
    catalogTV.dataArr = [self getArrByIndex:self.catalogTag];
    catalogTV.frame = CGRectMake(0, 0, UIScreenWidth, catalogTV.dataArr.count*44+40);
    catalogTV.selDelegate = self;
    [catalogTV reloadData];
    [self.catalogView addSubview:catalogTV];
    
    self.catalogViewHeight.constant = catalogTV.dataArr.count*44+40;
    
    _infoImgView.image = [UIImage imageNamed:[NSString stringWithFormat:@"course_%ld_new.jpg", self.catalogTag+1]];
    
    CGSize imageSize=_infoImgView.image.size;
    if(imageSize.width!=0)
//        self.conentViewHeight.constant = (imageSize.height/imageSize.width)*UIScreenWidth + self.catalogViewHeight.constant +self.btnBgView.frame.size.height + self.videoBgView.frame.size.height;
        self.conentViewHeight.constant = UIScreenHeight-20;
    self.ScrollBottomView.constant = (imageSize.height/imageSize.width)*UIScreenWidth + self.catalogViewHeight.constant;
}

#pragma mark ---- SelectDelegate <NSObject>//协议
-(void)didSelectbyRow:(NSInteger)row
{
    NSLog(@"选择了第%d个课程", row);
    _rowNow = row;
    if(_videoBtn.selected)
    {
        NSURL * url = [NSURL URLWithString:[_vediodDataArr objectAtIndex:row]];
        NSURLRequest * request = [NSURLRequest requestWithURL:url];
        [_webview loadRequest:request];
    }
    else
    {
        NSString *mp3Path =[[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp3"];
        //把音频文件转换成url格式
        NSURL *url = [NSURL fileURLWithPath:mp3Path];
        //self.moviePlayerVC.player = [[AVPlayer alloc] initWithURL:url];
        
        NSURLRequest * request = [NSURLRequest requestWithURL:url];
        [_webview loadRequest:request];
    }
}

#pragma mark ---- 初始化视频容器，默认加载第一个视频
-(void)initVedioView
{
    SVProgressHUD_SHOW
    NSArray *catArr1 = [[NSArray alloc]initWithObjects:@"http://player.youku.com/embed/XMzc2NDU1MjU2",@"http://player.youku.com/embed/XMzc2NDU1Mjky",@"http://player.youku.com/embed/XMzc2NDU2MjIw",@"http://player.youku.com/embed/XMzc2NDU1ODM2",@"http://player.youku.com/embed/XMzc2NDU3MDYw", nil];
    NSArray *catArr2 = [[NSArray alloc]initWithObjects:@"http://player.youku.com/embed/XNDkyNTUyNDY4",@"http://player.youku.com/embed/XNDkyNTUyNjY4",@"http://player.youku.com/embed/XNDkyNTUyODEy",@"http://player.youku.com/embed/XNDkyNTUzMjMy",@"http://player.youku.com/embed/XNDkyNTUzMzU2", nil];
    NSArray *catArr3 =[[NSArray alloc]initWithObjects:@"http://player.youku.com/embed/XMzc2OTAwNjQ4",@"http://player.youku.com/embed/XMzc2OTAwNzM2",@"http://player.youku.com/embed/XMzc2OTAxODQw",@"http://player.youku.com/embed/XMzc2OTAyMTAw",@"http://player.youku.com/embed/XMzc2OTA2MTY4", nil];
    NSArray *catArr4 = [[NSArray alloc]initWithObjects:@"http://player.youku.com/embed/XNDk5MDYyODMy",@"http://player.youku.com/embed/XNDk5MDYzNzQ0",@"http://player.youku.com/embed/XNDk5MDYzODc2",@"http://player.youku.com/embed/XNDk5MDYzODk2", nil];
    NSArray *allArr =  [[NSArray alloc]initWithObjects:catArr1,catArr2,catArr3,catArr4,nil];
    _vediodDataArr = [allArr objectAtIndex:_catalogTag];
    
//    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
//    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
//    [audioSession setActive:YES error:nil];
//    self.audioPlayer.delegate = self;
//    self.moviePlayerVC.delegate = self;
//    NSString *newVideoUrl = [_vediodDataArr objectAtIndex:0];
//    self.moviePlayerVC = [[AVPlayerViewController alloc] init];
//    self.moviePlayerVC.player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:newVideoUrl]];
//    // 设置播放器的frame
//    self.moviePlayerVC.view.frame = CGRectMake(0, 30, UIScreenWidth, UIScreenWidth/2-30);
//    [_videoBgView addSubview:self.moviePlayerVC.view];
//    [_videoBgView bringSubviewToFront:_btnback];
    
    
    _webview = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenWidth/2)];
    // 自动队页面进行缩放以适应屏幕
    _webview.scalesPageToFit = YES;
    _webview.userInteractionEnabled = YES;
    _webview.opaque = YES;
    _webview.allowsInlineMediaPlayback = YES;
    _webview.delegate = self;
    _webview.backgroundColor = [UIColor clearColor];
    _webview.opaque = NO;
    [_webview setBackgroundColor:[UIColor blackColor]];
    _webview.scrollView.scrollEnabled = NO;
    [_videoBgView addSubview:_webview];
    NSURL * url = [NSURL URLWithString:[_vediodDataArr objectAtIndex:0]];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    [_webview loadRequest:request];
    [_videoBgView bringSubviewToFront:_topView];
    [_videoBgView bringSubviewToFront:_btnback];
    [_videoBgView bringSubviewToFront:_btnShare];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(videoFinished:)
                                                 name:UIWindowDidBecomeHiddenNotification
                                               object:self.view.window];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(videoStarted:)
                                                 name:UIWindowDidBecomeVisibleNotification
                                               object:self.view.window];
   
}
- (void)videoStarted:(NSNotification *)notification {
    NSLog(@"视频 开始 播放");
}

//播放完成，小于11的系统会上移
- (void)videoFinished:(NSNotification *)notification {
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
    if([phoneVersion floatValue]<11)
    {
        _scrollTop.constant = 20;
    }
}
#pragma mark ---- 音视频按钮点击事件
- (IBAction)videoBtnAction:(id)sender {
    BOOL select = _videoBtn.selected;
    _audioBtn.selected = select;
    _videoBtn.selected = !select;
    
    NSLog(@"播放视频");
//    NSString *newVideoUrl = [_vediodDataArr objectAtIndex:_rowNow];
//    self.moviePlayerVC.player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:newVideoUrl]];
    
    NSURL * url = [NSURL URLWithString:[_vediodDataArr objectAtIndex:_rowNow]];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    [_webview loadRequest:request];
}

- (IBAction)audioBtnAction:(id)sender {
    BOOL select = _audioBtn.selected;
    _videoBtn.selected = select;
    _audioBtn.selected = !select;
    
    NSLog(@"播放音频");
    NSString *mp3Path =[[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp3"];
    //把音频文件转换成url格式
    NSURL *url = [NSURL fileURLWithPath:mp3Path];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    [_webview loadRequest:request];
    //self.moviePlayerVC.player = [[AVPlayer alloc] initWithURL:url];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//  颜色转换为背景图片
- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

//
-(NSArray *)getArrByIndex:(NSInteger)row
{
    NSArray *catalogArr1 = [NSArray arrayWithObjects:@"金融和保险在我们经济和社会中的强大作用", @"风险管理中的普遍原理:风险聚集和对冲", @"金融中的科技与发明", @"投资组合多元化和辅助性的金融机构", @"保险:典型的风险管理制度", nil];
    
    NSArray *catalogArr2 = [NSArray arrayWithObjects:@"潜在的资金流", @"直接法", @"现金流量表分析", @"现金流量表分析", @"资产负债表分析", nil];
    
    NSArray *catalogArr3 = [NSArray arrayWithObjects:@"导论-五个入门结论", @"学会换位思考", @"迭代剔除和中位选民定理", @"足球比赛与商业合作之最佳对策", @"纳什均衡之坏风气与银行挤兑", nil];
    
    NSArray *catalogArr4 = [NSArray arrayWithObjects:@"联邦储蓄和金融危机:美联储的起源与使命", @"联邦储蓄和金融危机:二战后的美联储", @"美联储对金融危机的应对", @"危机的后果", nil];
    
    if(row == 0)
        return catalogArr1;
    else if(row == 1)
        return catalogArr2;
    else if(row == 2)
        return catalogArr3;
    else if(row == 3)
        return catalogArr4;
    else
        return nil;
}
#pragma mark ---- 视频加载完成
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    SVProgressHUD_HIDE
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    SVProgressHUD_HIDE
}

- (IBAction)btnbackClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)btnShareClick:(id)sender {
     [HUD showAlertWithTitle:DEFAULT_ALERT_MESSAGE];
}
-(void)viewWillDisappear:(BOOL)animated
{
    _webview = nil;
    [_webview removeFromSuperview];
}
@end
